<template>
  <div class="global_bg">
    <VantNavigationBar title="发布动态"></VantNavigationBar>
    <van-cell-group inset class="mt1">
      <!-- 商品描述 -->
      <van-cell>
        <textarea
          :maxlength="300"
          cols="10rem"
          style="width: 95%; border: 0"
          rows="8"
          placeholder="分享一下你的动态吧！"
          v-model="dynamicInfo.active_content"
        />
      </van-cell>
      <!-- 图片上传 -->
      <van-cell>
        <van-uploader
          v-model="fileList"
          multiple
          :max-count="1"
          :after-read="afterRead"
        />
      </van-cell>
    </van-cell-group>
    <div class="logn_btn fts1 tc" @click="goUpload">发布</div>
  </div>
</template>
<script>
import VantNavigationBar from '@/components/Navbar'
import { Cell, CellGroup, Uploader, Toast, showToast } from 'vant'
import mine from '@/api/mine'
import { ref } from 'vue'
import moment from 'moment'
import api from '@/api/api.js'
export default {
  components: {
    VantNavigationBar,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Uploader.name]: Uploader,
    [Toast.name]: Toast,
    [showToast.name]: showToast,
  },
  setup() {
    // 格式化时间
    const formattedDate = () => {
      return moment().format('YYYY-MM-DD HH:mm:ss')
    }
    const fileList = ref([])
    const dynamicInfo = ref({
      active_content: '',
      active_image: '',
      add_time: formattedDate(Date.now()),
    })

    const afterRead = (file) => {
      // 创建 FormData 对象，用于发送文件数据
      const formData = new FormData()
      formData.append('file', file.file)
      api
        .uploadImage(formData)
        .then((res) => {
          dynamicInfo.value.active_image = res.filename
        })
        .catch((error) => {
          console.error('Error:', error)
          // 处理错误情况
        })
    }
    const goUpload = () => {
      if (dynamicInfo.value.active_image !== '') {
        dynamicInfo.value.active_image =
          'user/' + dynamicInfo.value.active_image
      }
      if (!dynamicInfo.value.active_content) {
        showToast('请填写内容！')
        return
      }
      mine.releaseDynamic(dynamicInfo.value).then((res) => {
        if (res.status === 200) {
          showToast(res.msg)
          dynamicInfo.value.active_content = ''
          fileList.value = []
        }
      })
    }

    return {
      goUpload,
      dynamicInfo,
      formattedDate,
      fileList,
      afterRead,
    }
  },
}
</script>
<style></style>
